<?php


namespace app\controller\admin;


use app\BaseController;
use app\services\utils\Oss;
use think\facade\App;
use think\facade\Filesystem;
use think\Request;

error_reporting(1);

class ImageController extends BaseController
{

    /**
     * 图片上传
     * @return \think\response\Json
     */
    public function upload()
    {
        try {
            $file = $this->request->file('image');
            $saveName = Filesystem::putFile('goods-taste-img', $file);
            $filePath = App::getRootPath() . "runtime/storage/" . $saveName;
            $oss = new Oss();
            $result = $oss->uploadImage($saveName, $filePath);
            return $this->success($result);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage(), $exception->getCode());
        }
    }

    /**
     * 上传图片到本地
     * @return \think\response\Json
     */
    public function uploadImg()
    {
        try {
            $file = $this->request->file('image');
            $ext = $file->extension();
            validate(['image' => 'fileExt:jpg,jpeg,png,xlsx,xls'])->check(['image' => $file]);
            $savename = \think\facade\Filesystem::disk("public")->putFile('uploads', $file);
            $savename = str_replace('\\','/',$savename);
            return $this->success(['src' => '/storage/' . $savename, 'ext' => $ext]);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage(), $exception->getCode());
        }
    }

    /**
     * 上传图片到本地
     * @return \think\response\Json
     */
    public function uploadImage()
    {
        try {
            $file = $this->request->file('image');
            $ext = $file->extension();
            validate(['image' => 'fileExt:jpg,jpeg,png,xlsx,xls'])->check(['image' => $file]);
            $savename = \think\facade\Filesystem::disk("public")->putFile('banner', $file);
            return json([
                "errno" => 0,
                "data" => [
                    'url' => $this->request->domain().'/storage/' . $savename,
                ]
            ]);
        } catch (\Exception $exception) {
            return json([
                "errno" => 1,
                "message" => $exception->getMessage()
            ]);
        }
    }
}
